﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Linq.Expressions;
using ICE.Vacations.DataBase;
using ICE.Vacations.Helper.Services;
using ICE.Vacations.InfoImage;
using ICE.Vacations.Request;
namespace MvcApplication1.Controllers
{
    public class jQGridController : Controller
    {
        public Documents documents = new Documents();
        [HttpPost]
        public ActionResult LoadjqData(string sidx, string sord, int page, int rows,
                bool _search, string searchField, string searchOper, string searchString)
        {
            // Get the list of students
            documents.SelectAll();
            // StudentManager.consultar();
            var students = documents.GetDocuments().AsQueryable();

            // If search, filter the list against the search condition.
            // Only "contains" search is implemented here.
            var filteredStudents = students;
            if (_search)
            {
                filteredStudents = students.Where(s =>
                    (typeof(Documents).GetProperty(searchField).GetValue(s, null) == null) ? false :
                        typeof(Documents).GetProperty(searchField).GetValue(s, null)
                        .ToString().Contains(searchString));
            }

            // Sort the student list
            var sortedStudents = SortIQueryable<Documents>(filteredStudents, sidx, sord);

            // Calculate the total number of pages
            var totalRecords = filteredStudents.Count();
            var totalPages = (int)Math.Ceiling((double)totalRecords / (double)rows);

            // Prepare the data to fit the requirement of jQGrid
            var data = (from s in sortedStudents
                        select new
                        {
                            id = s.requestID,
                            cell = new object[] { s.requestID,s.username, s.employeeID,
                                s.totalDays,s.totalRequestedDays,s.dateFrom,s.dateTo, s.dateRegistered.ToString(),
                                s.state,
                            s.aprobador1, s.aprobador2,s.aprobador3 }
                        }).ToArray();

            // Send the data to the jQGrid
            var jsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = data.Skip((page - 1) * rows).Take(rows)
            };

            return Json(jsonData);
        }

        // Utility method to sort IQueryable given a field name as "string"
        // May consider to put in a cental place to be shared
        private IQueryable<T> SortIQueryable<T>(IQueryable<T> data, string fieldName, string sortOrder)
        {
            if (string.IsNullOrWhiteSpace(fieldName)) return data;
            if (string.IsNullOrWhiteSpace(sortOrder)) return data;

            var param = Expression.Parameter(typeof(T), "i");
            Expression conversion = Expression.Convert(Expression.Property(param, fieldName), typeof(object));
            var mySortExpression = Expression.Lambda<Func<T, object>>(conversion, param);

            return (sortOrder == "desc") ? data.OrderByDescending(mySortExpression)
                : data.OrderBy(mySortExpression);
        }

    }
}
